package com.googlecode.maurersmarbles;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.graphics.Point;
import android.graphics.Rect;

public class LinearCardsDisplay extends CardsDisplay {

	/**
	 * The scale size of the space between cards compared to the cards display
	 * width.
	 */
	private static final float CARD_SPACE_SCALE_FACTOR = 0.015f;
	/**
	 * The size of the space between cards.
	 */
	private double cardSpaceWidth;
	/**
	 * The list that contains the bounding box for each card.
	 */
	private Map<Card, Rect> cardToBoundingBox = new HashMap<Card, Rect>();

	/**
	 * Creates a new LinearCardsDisplay.
	 */
	public LinearCardsDisplay() {
		// do nothing
	}

	@Override
	public Card getCardAtScreenXY(int x, int y) {
		for (Map.Entry<Card, Rect> entry : cardToBoundingBox.entrySet()) {
			if (entry.getValue().contains(x, y)) {
				return entry.getKey();
			}
		}
		return null;
	}

	@Override
	public Point[] getCardCornersOnScreen(Card card) {
		if (!cardToBoundingBox.containsKey(card)) {
			return null;
		}
		Rect rect = cardToBoundingBox.get(card);
		Point[] corners = new Point[4];
		corners[0] = new Point(rect.left, rect.top);
		corners[1] = new Point(rect.right, rect.top);
		corners[2] = new Point(rect.right, rect.bottom);
		corners[3] = new Point(rect.left, rect.bottom);
		return corners;
	}

	@Override
	public void setCards(List<Card> cards) {

		// clear the previous list of cards and bounding boxes
		cardToBoundingBox.clear();

		if (cards == null || cards.isEmpty()) {
			return;
		}

		// sort the cards
		Collections.sort(cards, new CardComparator());

		double neededWidth = (cards.size() * cardWidth)
				+ ((cards.size() - 1) * cardSpaceWidth);
		double cardX = outerRect.left
				+ ((outerRect.width() - neededWidth) / 2.0);
		double cardY = outerRect.top
				+ ((outerRect.height() - cardHeight) / 2.0);

		for (Card card : cards) {
			Rect rect = new Rect((int) cardX, (int) cardY,
					(int) (cardX + cardWidth), (int) (cardY + cardHeight));
			cardToBoundingBox.put(card, rect);
			cardX += cardWidth + cardSpaceWidth;
		}

	}

	@Override
	public void setLocationAndSize(int startX, int startY, int width, int height) {
		super.setLocationAndSize(startX, startY, width, height);
		// TODO Should we add a check to make sure the display height is big
		// enough?
		cardSpaceWidth = CARD_SPACE_SCALE_FACTOR * width;
		cardWidth = (width - (cardSpaceWidth * (MAX_NUMBER_OF_CARDS - 1)))
				/ MAX_NUMBER_OF_CARDS;
		cardHeight = cardWidth / Card.WIDTH_TO_HEIGHT_RATIO;
	}

}
